<template>
  <div class="index-box d-flex" ref="index">
    <div class="leftBox" :style="{'width': leftTreeShow?'200px':'0px'}">
      <div class="tree-box">
        <el-tree :data="treeList" :props="defaultProps" current-node-key="" node-key="categoryId"  default-expand-all @node-click="handleNodeClick" :expand-on-click-node="false"></el-tree>
      </div>
    </div>
    <div class="rightBox">
        <div class="table-box" >
          <div class="search" ref="search">
            <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent
              class="demo-form-inline" id="searchBox">
              <el-form-item prop="name">
              	<el-input v-model="searchForm.name" placeholder="请输入文章名称" clearable />
              </el-form-item>

              <el-form-item prop="applyTime">
                <el-date-picker v-model="applyTime" type="daterange" align="right" unlink-panels range-separator="至"
                  start-placeholder="更新开始日期" end-placeholder="更新结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
              <el-form-item prop="status">
              	<el-select v-model="searchForm.status" placeholder="状态" clearable >
              		<el-option label="启用" value="1" /></el-option>
              		<el-option label="禁用" value="2" /></el-option>
              	</el-select>
              </el-form-item>

              <el-form-item>
              	<el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">搜索</el-button>
              	<el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
              </el-form-item>

            </el-form>
          </div>
          <div class="actionBtn" ref="actionBtn">
            <div class="actionBtnLeft d-flex align-center">
                <MyLeftTreeRetract :leftTreeShow.sync="leftTreeShow"></MyLeftTreeRetract>
                <el-button type="primary" icon="el-icon-add" size="small" @click="handleAdd" v-has="'article:article:add'">添加文章</el-button>
            </div>
            <div class="actionBtnRight">
                <MyRefresh/>
                <MyTableColumnSet :tableColumn.sync="tableColumn" :hideTableColumn.sync="hideTableColumn" :tableColumnType.sync="tableColumnType"></MyTableColumnSet>
            </div>
          </div>
          <div class="table" ref="table">
            <el-table :data="dataList" style="width: 100%;" v-loading="loading" border :height="tableHeight"  default-expand-all stripe>
             <el-table-column label="infoId" align="center"  prop="infoId" width="220"/></el-table-column>
             <el-table-column prop="name" label="文章名称" v-if="!hideTableColumn.includes('img')" width="200"></el-table-column>

             <el-table-column prop="modifyDate" label="更新时间" v-if="!hideTableColumn.includes('applyTime')" sortable align="center">
               <template slot-scope="scope">
                 <span>{{ parseTime(scope.row.modifyDate) }}</span>
               </template>
             </el-table-column>
             <el-table-column label="状态"  v-if="!hideTableColumn.includes('status')" align="center">
               <template #default="scope">
                 <div class="d-flex justify-center">
                   <MySwitch :value.sync="scope.row.status" :id="scope.row.status" text="启用|禁用" textValue="1|2"  @changeStatus="handleChangeStatus(scope.row)"></MySwitch>
                 </div>
               </template>
             </el-table-column>

             <el-table-column label="操作" align="center" width="200"  fixed="right">
             	<template slot-scope="scope" >
             		<el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" v-has="'article:article:alter'">修改</el-button>
             		<el-button type="text" icon="el-icon-delete" @click="handleDelt(scope.row)" v-has="'article:article:del'">删除</el-button>
             		<el-button type="text" icon="el-icon-view" @click="handleLook(scope.row)" >查看</el-button>
             	</template>
             </el-table-column>
            </el-table>
          </div>
          <div class="page" ref="page">
             <MyPagination
               :total="total"
               :page.sync="searchForm.pageNum"
               :limit.sync="searchForm.pageSize"
               @pagination="dataInfo"
             />

          </div>
        </div>
    </div>


    <!-- 添加文章 -->
    <el-dialog :title="dialogTitle" :visible.sync="addArticleVisible" width="1100px" :close-on-click-modal="false" v-dialogDrag>
      <el-form id="formDialog" label-position="right" :model="user" :rules="rules" ref="user">
        <el-form-item label="文章分类:" prop="type" label-width="125px"  style="width:100%" >
            <el-select v-model="user.categoryId" clearable>
              <el-option v-for="item in categoryList" :label="item.name" :value="item.categoryId"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="文章名称:" prop="name" label-width="125px"  style="width:100%" >
           <el-input v-model="user.name" clearable placeholder="文章名称"></el-input>
        </el-form-item>
        <el-form-item label="上传图片:" prop="image" label-width="125px"  style="width:50%" v-if="user.categoryId!='1'">
          <MyUpImg :imagePreview='user.image'  @change="imageChange($event,'image')"></MyUpImg>
        </el-form-item>
        <el-form-item label="上传视频:" prop="videoSource" label-width="125px"  style="width:50%"  v-if="user.categoryId!='1'">
          <MyUpVideo :imagePreview='user.videoSource'  @change="imageChange($event,'videoSource')"></MyUpVideo>
        </el-form-item>

        <el-form-item label="文章详情:" prop="description" label-width="125px">
        <!--  <QuillEditor :value.sync="user.description" v-if="user.categoryId!='4'" /> -->
           <editor-bar v-model="user.description" @change="getEditor" ref="weditor" v-if="user.categoryId!='4'"></editor-bar>
          <el-input type="textarea" v-model="user.description" v-else rows="6"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" v-if="dialogTitle!='查看文章'">

        <el-button @click="addArticleVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="submitForm('user')" size="small" :loading="userLoading">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import common from '@/api/api';
  import { articleList,delAdvertis,advertisUpdateStatus,articleSave,articleUpdate,articleUpdateStatus,articleDelArticle } from '@/api/getData';
  import option from '../../common/option.js';
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import QuillEditor from '@/components/QuillEditor/quillEditor'

  import EditorBar from "@/components/Editor/Editor";
  export default {
     components: { Treeselect,QuillEditor,EditorBar },
    data() {
      return {
        loading: false,
        userLoading: false,
        leftTreeShow: true,
        tableColumn: [],
        hideTableColumn:[],/*自定义表格列需要隐藏的*/
        tableColumnType:'staffManagement',/*自定义表格列类型传参*/

        applyTime:[],
        searchForm: {
          contractId:'',
          name:'',
          status:'',
          pageNum: 1,
          pageSize: 20,
        },
        total: 0,
        treeList: [],
        tableHeight:400,//table 高度
        dataList:[],
        defaultProps: {
           children: 'children',
           label: 'name'
        },
        multipleSelection: '',

        user:{
          infoId:'',
          categoryId:"",
          name:"",
          image:'',
          videoSource:"",
          description:'',
        },
        rules: {
            name: [{required: true, message: '请输入文章名称',trigger: 'blur'}],
            description: [{required: true, message: '请输入文章详情',trigger: 'blur'}],
        },
        addArticleVisible:false,
        categoryList:[],
        dialogTitle:'',
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    mounted() {
      this.getSelect();
      this.dataInfo();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight - this.$refs.search.offsetHeight - this.$refs.actionBtn.offsetHeight - this.$refs.page.offsetHeight - 55;
      })
    },
    methods: {
      // 获取富文本内容
      getEditor(value) {
         this.user.description = value;
      },
      async dataInfo() {
        try {
          let data = this.addDateRange(this.searchForm, this.applyTime, 'startTime', 'endTime');
          this.loading = true;
          const result = await articleList(data);
          if (result.code == 200) {
            this.total = result.total;
            let data = result.rows;
            this.dataList = data;
          } else {
            this.$message.error(result.msg);
          }
          this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },
      getSelect() {
        this.getSelectList('article_category_key').then(res=>{
          let data = res.data;
          data.map(item=>{
            item.categoryId = item.dictValue,
            item.name = item.dictLabel
          })
          this.treeList = [{
            categoryId: '',
            children: data,
            name: "文章分类",
          }];
          this.categoryList = data;
        })
      },
      imageChange(path, name) {
        this.user[name] = path
      },
       submitForm(formName){/*申请好店推广位 提交*/
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.userLoading = true;
            let data = JSON.parse(JSON.stringify(this.user));
            data.description = JSON.stringify(data.description);
            if(!this.user.infoId){
                articleSave(data).then((result) => {
                  if (result.code == 200) {
                    this.$message.success(result.msg);
                    this.addArticleVisible = false;
                     this.dataInfo();
                  } else {
                    this.$message.error(result.msg);
                  }
                  this.userLoading = false;
                });
            }else{
              articleUpdate(data).then((result) => {
                if (result.code == 200) {
                  this.$message.success(result.msg);
                  this.addArticleVisible = false;
                   this.dataInfo();
                } else {
                  this.$message.error(result.msg);
                }
                this.userLoading = false;
              });
            }

          }
        })
      },
      async handleChangeStatus(row) {
        try {
          let data = {
            infoId: row.infoId,
            status: row.status
          }
          const result = await articleUpdateStatus(data);
          if (result.code == 200) {
            this.$message.success(result.msg);
          } else {
            this.$message.error(result.msg);
            row.status = !row.status;
          }
        } catch (err) {
          console.log(err)
        }
      },
      handleAdd(){
         this.dialogTitle = '添加文章';
         this.user.infoId = '';
         this.user.categoryId = this.searchForm.contractId?this.searchForm.contractId:'';
         this.user.name='';
         this.user.image='';
         this.user.videoSource="";
         this.user.description='';
         this.addArticleVisible = true;
      },
      handleEdit(row){
        this.dialogTitle = '修改文章';
        this.user.infoId = row.infoId;
        this.user.categoryId = row.categoryId;
        this.user.name=row.name;
        this.user.image=row.image;
        this.user.videoSource=row.videoSource;
        this.user.description= JSON.parse(row.description);
         this.addArticleVisible = true;
      },
      handleLook(row){
        this.dialogTitle = '查看文章';
        this.user.infoId = row.infoId;
        this.user.categoryId = Number(row.categoryId);
        this.user.name=row.name;
        this.user.image=row.image;
        this.user.videoSource=row.videoSource;
        this.user.description= JSON.parse(row.description);
         this.addArticleVisible = true;
      },
      handleDelt(row){
          this.$confirm('您确定要删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            articleDelArticle({infoId:row.infoId}).then((result) => {
              if (result.code == '200') {
                   this.dataInfo();
                   this.$message({
                     message: result.msg,
                     type: 'success'
                   });
               }else{
                  this.$message.error(result.msg);
               }
           });
          }).catch(() => {
              console.log(1);
          });
      },
      resetQuery() {
        this.applyTime = [];
        this.auditTime = [];
        this.resetForm("searchForm");
        this.dataInfo();
      },

      handleSearch() {
        this.searchForm.pageNum= 1;
        this.dataInfo();
      },
      resetFormDialog(formName) {
        this.$refs[formName].resetFields();
      },

      handleNodeClick(data){/*树节点点击事件*/
       this.searchForm.contractId = data.categoryId;
       this.searchForm.page = 1;
       this.dataInfo();
      },
    }
  }
</script>

<style scoped lang="scss">
  .index-box{
    padding:0px!important;
    margin-left:0px;
  }
  .tree-box /deep/ .el-tree-node{
     background: #D8E4DD;
  }
  .tree-box> /deep/ .el-tree>.el-tree-node{
    padding:10px;
  }
  .tree-box> /deep/ .el-tree .is-current{
    background:#fff;
  }
  .table-box{
    padding:15px
  }
  .down{
    color: #909399;
    cursor: pointer;
    text-decoration:underline;
  }
  .down:hover{
    color: #a6a9ad;
  }
  .up{
    color:#61997A;
    cursor: pointer;
    text-decoration:underline;
  }
  .up:hover{
    color:#81ad95;
  }
</style>
